var m3958_host = 'http://dy.m3958.com';

(function(){
	var hr = window.location.href.toUpperCase();
	if(hr.indexOf('8888') == -1){
		if(hr.indexOf('debug=true') != -1){
			m3958_host = 'file:///E:/eclipse-jee-helios-SR1-win32/xyzcms/war';
		}
	}else{
		m3958_host = 'http://127.0.0.1:8888';
	}
})();

var fireImgFetchGlobalEvent = function (e, param) {//'imgPreFetched'
	  YUI().use('event-custom', function (Y) {
	    var publisher = new Y.EventTarget();
	    publisher.publish(e, {
	      broadcast:  2,   // global notification
	      emitFacade: true // emit a facade so we get the event target
	    }).fire(param);
	  });
};
	
YUI({combine: true,
/*	comboBase: m3958_host + '/combo/yui?',*/
	"maxURLLength":1024,
	groups:{
//        myapp: {
//            base: './wf/intl/',
//            modules : {
//                "translator" : {
//                    path: 'translator/translator.js',
//                    lang: ["en","zh","zh-Hant", "ja", "ko"]
//                }
//            }
//        }
//        ,
    	mymenu : {
    		combine : false,
	        modules: {
	            "node-menunav-core-css": {
	                type: "css",
	                path: "node-menunav/assets/node-menunav-core.css"
	            },
	            "custommenunavskin": {
	                type: "css",
	                fullpath: "/m3958-module-css/dayanmenu.css",
	                supersedes: ['skin-sam-node-menunav']//替換對象
	            }
    		}
        }
    }
}).use('scrollview','message-panel','article-dialog','article-panel','section-panel','event','event-base-ie','node-base','node-event-delegate','event-move','event-delegate','overlay','javascript-site','javascript-section','javascript-article','section-widget','bing-box-widget','bing-box-widget','bing-box-group-component','mouse-move-delay','yui-bg-slideshow','transition','slide-control','node-menunav','node-menunav-core-css','custommenunavskin',function(Y){
	Y.namespace('M3958.cfg').host = m3958_host;
	var body = Y.one('body');
	var vr = body.get('viewportRegion');
	body.set('width',vr.width);
	body.set('height',vr.height);
	
	var screen = window.screen,
		sratio = screen.availWidth / screen.availHeight,
		ssize;
	if(sratio > 1.75){//1.777
		ssize = 'kp';//宽屏
	}else{//1.333
		ssize = 'fp'; //方屏
	}
	
	Y.namespace("M3958.DAYAN").config = {screen:ssize};
	
	Y.M3958.DAYAN.siteId = 74067;
	
	var messagePanel = Y.M3958.DAYAN.messagePanel = new Y.M3958.MessagePanel({
        bodyContent: '<div class="message icon-warn">Are you sure you want to [take some action]?</div>',
        width      : 410,
        zIndex     : 1000,
        centered   : true,
        modal      : false, // modal behavior
        render     : true,
        visible    : false, // make visible explicitly with .show()
	    buttons: [
	        {
	            value  : '知道了',
	            name : 'okay',
	            section: Y.WidgetStdMod.FOOTER,
	            action : function (e) {
	                e.preventDefault();
	                messagePanel.hide();
	            }
	        }
	    ]
    });
	
	var jsite = new Y.M3958.JavascriptSite({siteId : Y.M3958.DAYAN.siteId}),
		dayanScrollView,
		slideControl = new Y.M3958.SlideControl({width:65,autoSlide:true,zIndex:100}),
		bgslide = new Y.M3958.YuiBgSlideShow({slideControl : slideControl,
											autoSlide : false,visible:false,zIndex : 0,preFetchNum:1}),
		bingBoxGroup = new Y.M3958.BingBoxGroupComponent({zIndex:100}),
		MyOverlay = Y.Base.create("myoverlay", Y.Overlay,[],{},{}),
		fixFooter = new MyOverlay({
	        // Specify a reference to a node which already exists 
	        // on the page and contains header/body/footer content
	        srcNode:"#fix-footer",
	
	        // Also set some of the attributes inherited from
	        // the base Widget class.
	        visible:false,
	        width:"100%",
	        zIndex : 50
	    });
    var a = Y.WidgetPositionAlign;
    
    fixFooter.set("align",{points:[a.BC, a.BC]})
    fixFooter.render();
    fixFooter.show();
    
    var dayanMenu = Y.one("#dayan-menu"),
    	dayanMenuClosex = dayanMenu.one('.closex');
    
    dayanMenu.plug(Y.Plugin.NodeMenuNav);
    
    function _createSectionPanel(){
		var sectionPanel = Y.M3958.DAYAN.sectionPanel; 
		if(!sectionPanel){
			var xy = dayanMenu.getXY();
	    	sectionPanel = Y.M3958.DAYAN.sectionPanel = new Y.M3958.SectionPanel({zIndex:101,
	    		width : 600,
	    		xy:[xy[0] + 230,xy[1]],
	    		plugins : [Y.Plugin.Drag],
	    		visible : true,
	    		modal  : false
	    		/*,
	    		buttons:[{
	                    value  : '<span class="yui3-button-icon"></span>',
	                    section: 'header',
	                    action : function (e) {
	                        e.preventDefault();
	                        sectionPanel.hide(true);
	                    },
	                    classNames : ['yui3-button-close']
	                }]*/});
	    	sectionPanel.render();
		}
		return sectionPanel;
    }
    
    function _showSection(sid){
		var sectionPanel =  _createSectionPanel();
		if(!sectionPanel.get('visible')){
			sectionPanel.show();
		}
		if(sectionPanel.get('section') && sectionPanel.get('section').gett('id') == sid){
			;
		}else{
			var section = jsite.findSection(sid);
			sectionPanel.set('section',section);
		}
    }
    
    function _showArticleDialog(){
    	var articleDialog = Y.M3958.DAYAN.articleDialog;
    	if(!articleDialog){
            articleDialog = Y.M3958.DAYAN.articleDialog = new Y.M3958.ArticleDialog({
                srcNode      : '#m3958-article-dialog-content',
                headerContent: '说点什么',
                width        : 450,
                zIndex       : 200,
                centered     : true,
                modal        : false,
                visible      : false,
                render       : true,
                plugins      : [Y.Plugin.Drag],
                relationModelId : 75193, //43201
                siteId : Y.M3958.DAYAN.siteId //8605
            });
    	}
        articleDialog.show();
        articleDialog.refreshCaptch();
    }
    
    (function(){
    	var timer = null,
    		dayanMenuHidden = false;
    	dayanMenu.on('mouseenter',function(e){
    		if(timer){//如果正准备隐藏，取消隐藏。
    			timer.cancel();
    			timer = null;
    		}
    		if(!dayanMenuHidden){
    			dayanMenuClosex.removeClass('closex-hidden');
    		}else{
    			dayanMenu.transition({
    			    easing: 'ease-in',
    			    duration: 0.5, // seconds
    			    left: '15px'
    			},function(){dayanMenuHidden = false;});
    		}
    	});
    	
    	dayanMenu.on('mouseleave',function(e){
    		if(dayanMenuHidden)return;
    		if(timer){//如果正在隐藏中，那么重新开始计时。
    			timer.cancel();
    			timer = null;
    		}
    		timer = Y.later(1000,this,function(){
    			dayanMenuClosex.addClass('closex-hidden');
    		});
    	});
    	
    	dayanMenuClosex.on('mouseenter',function(e){
    		if(timer){//如果正处在隐藏中，取消它。
    			timer.cancel();
    			timer = null;
    		}
    	});
    	
    	dayanMenuClosex.on('click',function(){
    		dayanMenuClosex.addClass('closex-hidden');
			dayanMenu.transition({
			    easing: 'ease-in',
			    duration: 1, // seconds
			    left: '-160px'
			},function(){dayanMenuHidden = true;});
    	});
    	
    	dayanMenu.delegate('click',function(e){
    		var mnode = e.currentTarget;
    		if(mnode.get('href').indexOf('/vote?voteid') == -1){
    			e.preventDefault();
    		}else{
    			return;
    		}
    		if(mnode.get('id') == 'dayan-news'){
    			_showSection(75034);
    		}else if(mnode.get('id') == 'dayan-nong-chan-pin'){
    			var section = jsite.findSection(75063);
    			section.fetchArticles(0,5,{usage:['slide']});
    		}else if(mnode.get('id') == 'dayan-people-say'){
    			_showSection(75193);
    		}else if(mnode.get('id') == 'dayan-you-say'){
    			_showArticleDialog();
    		}else if(mnode.get('id') == 'dayan-activitis'){
    			if(!dayanScrollView)return;
    			Y.one('#scrollview-container').removeClass('scrollview-container-loading');
    		}
    	},'a.yui3-menuitem-content');
    })();
    
    var firstFetch = true;
	Y.Global.on('imgPreFetched',function(e){
		Y.one('#preload-display').addClass('preload-display-hide');
		if(firstFetch){
			firstFetch = false;
			var dayanLogo = Y.one('#dayan-logo');
			dayanLogo.hide(true);
			dayanLogo.removeClass('dayan-logo-loading');
			dayanLogo.show(true);
			
			dayanMenu.removeClass('dayan-menu-loading');
			dayanMenu.transition({
				    easing: 'ease-in',
				    duration: 2, // seconds
				    left: '15px'
				}, function() {
					this.removeClass('dayan-menu-hidden');
				});

			var ca = Y.one('#cycle-arrow');
			var endy = (vr.height - 130) + 'px';
			ca.removeClass('cycle-arrow-loading');
			ca.setXY([vr.width - 100,0]);
			ca.transition({
			    easing: 'ease-in',
			    duration: 3, // seconds
			    top: endy
			},function(){
				this.remove();
			});

		}
	});
	
	bgslide.on('transitionStart',function(e){
		bingBoxGroup.set('article',e.article);
	});
	
	bgslide.render();
//	jsite.set('bgSlide',bgslide);
//	this.fire('sectionArticleFetched',{section:section,articles:articles,extra:extra});
// global event
	jsite.on('sectionArticleFetched',function(e){
		var usages = e.extra.usage,
			slideUsage = Y.Array.find(usages,function(item){
				if(item == 'slide'){
					return true;
				}
			}),
			activityUsage =Y.Array.find(usages,function(item){
				if(item == 'activity'){
					return true;
				}
			});
		
		if(slideUsage){
			if(e.section.gett('id') == 74087){
				var ars = e.articles;
				var rnd = Math.floor(ars.length * Math.random());
				if(rnd === 0){
					;
				}else{
					var a = e.articles[rnd];
					e.articles[rnd] = e.articles[0];
					e.articles[0] = a;
				}
			}
			bgslide.articleArrival(e.section,e.articles);
		}
		if(activityUsage){
			var tpl = '<li><a href="{url}" title="AC/DC | The Official AC/DC Site">{title}</a> <span class="scroll-view-date">5月15日</span></li>',
				cc = Y.Array.reduce(e.articles,'',function(prev,a){
					return prev + Y.Lang.sub(tpl,{title : a.gett('title'),url:a.gett('url')});
				});
			var cn = Y.one('#scrollview-content ul');
			cn.setContent(cc);
//			Y.log(cn.get('region').height);
//			Y.one('#scrollview-container').removeClass('scrollview-container-loading');
			_createDayanScrollView(Y.one('#scrollview-content').get('region').height);
		}
	});
	
	jsite.on('siteReady',function(e){
		var section = jsite.findSection(74087);
//		Y.log(section.gett('id'));
		section.fetchArticles(0,5,{usage:['slide','activity']});//既可以单独监听，也可以站点范围的监听。
	});
	
	jsite.fetchSite();
	
	Y.one('.yui3-yuibgslideshow-content').delegate("gesturemovestart",function(e){
		var item = e.currentTarget;
		if(!item.hasClass('bg-slide-img'))return;
		item.setData("swipeStart", e.pageX);
        // Prevent Text Selection in IE
        item.once("selectstart", function(e) {
            e.preventDefault();
        });
        item.once("gesturemoveend", function(e) {
        	if(!item.hasClass('bg-slide-img'))return;
            var swipeStart = item.getData("swipeStart"),
                swipeEnd = e.pageX,
                isSwipeLeft = (swipeStart - swipeEnd) > 10,
                isSwipeRight = (swipeEnd - swipeStart) > 10;

            if (isSwipeLeft) {
            	slideControl.gotoNext();
            }
            if(isSwipeRight){
            	slideControl.backToPrev();
            }
        });
	},'.bg-slide-img',{preventDefault:true});
	
	
	function _createDayanScrollView(height){
		
		Y.one('.view-close-btn').on('click',function(e){
			e.preventDefault();
			Y.one('#scrollview-container').addClass('scrollview-container-loading');
		});
		if(height && height < 210){
			height = height - 5;
		}else{
			height = 210;
		}
        var scrollView = dayanScrollView = new Y.ScrollView({
            id: "scrollview",
            srcNode: '#scrollview-content',
            height: height,
            flick: {
                minDistance:10,
                minVelocity:0.3,
                axis: "y"
            }
        });

        scrollView.render();
        
        var content = scrollView.get("contentBox"); 

				content.delegate("click", function(e) {
				    // Prevent links from navigating as part of a scroll gesture
				    if (Math.abs(scrollView.lastScrolledAmt) > 2) {
				        e.preventDefault();
						Y.log("Link behavior suppressed.")
				    }
				}, "a");

        content.delegate("mousedown", function(e) {
            // Prevent default anchor drag behavior, on browsers which let you drag anchors to the desktop
            e.preventDefault();
        }, "a");
        
        content.delegate("click", function(e) {
            // Prevent default anchor drag behavior, on browsers which let you drag anchors to the desktop
            e.preventDefault();
        }, "a");
	}

//    menu.get("ownerDocument").get("documentElement").removeClass("yui3-loading");

});